# -*- coding: utf-8 -*-
# @file   : InstrySrvany.py
# @author : songxulin
# @date   : 2021:08:21 14:00:00
# @version: 1.0
# @desc   : wimdows 服务注册
import locale
import os
import subprocess
import sys
import urllib.request


class ServicesData(object):
    """
        service_name 服务名称、
        app_directory 服务目录
        application 服务地址
        app_parameters 参数
    """

    def __init__(self, service_name, app_directory, application, app_parameters):
        self.service_name = service_name
        self.application = application
        self.app_directory = app_directory
        self.app_parameters = app_parameters


def reg_servers(server_name):
    if not os.path.exists("C:\\Program Files (x86)\\srvany"):
        os.mkdir("C:\\Program Files (x86)\\srvany")

    os.chdir("C:\\Program Files (x86)\\srvany")
    # 下载srvany.exe
    if not os.path.exists("C:\\Program Files (x86)\\srvany\\srvany.exe"):
        b64_text = get_data_by_url("http://test-erp.hbo-erp.com/upload-service/overlay/srvany.exe")
        f = open("srvany.exe", 'wb+')
        f.write(b64_text)
        f.close()
    # 下载instsrv.exe
    if not os.path.exists("C:\\Program Files (x86)\\srvany\\instsrv.exe"):
        b64_text = get_data_by_url("http://test-erp.hbo-erp.com/upload-service/overlay/instsrv.exe")
        f = open("instsrv.exe", 'wb+')
        f.write(b64_text)
        f.close()
    return run_batch(
        '"C:\\Program Files (x86)\\srvany\\instsrv.exe" %s "C:\\Program Files (x86)\\srvany\\srvany.exe"' % server_name)


def get_data_by_url(url):
    """从url中获取数据"""
    header = {
        'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }  # 头部信息
    request = urllib.request.Request(url=url, headers=header)  # 请求处理
    b64_text = urllib.request.urlopen(request).read()  # 读取结果
    return b64_text


def run_reg(services_data: ServicesData):
    reg_text = 'Windows Registry Editor Version 5.00\n' + \
    '[HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\%s\\Parameters]\n' % services_data.service_name + \
    '"AppParameters"="%s"\n' % services_data.app_parameters + \
    '"AppDirectory"="%s"\n' % services_data.app_directory + \
               '"Application"="%s"\n' % services_data.application

    current_path = "C:"
    reg_file_full_path = current_path + "\\tmp.reg"
    f = open(reg_file_full_path, mode='w', encoding='utf-8')
    f.write(reg_text)
    f.close()

    command = "regedit /s" + reg_file_full_path

    s = run_batch(command)
    os.remove(reg_file_full_path)
    return s
    # """设置自启动"""
    # key = winreg.OpenKeyEx(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\HboSoft")
    # # 给键添加键值
    # new_key = winreg.CreateKey(key, "Parameters")
    # # 设置值
    # winreg.SetValueEx(new_key, "AppDirectory", 0, winreg.REG_SZ, "C:\\HboSoft")
    # winreg.SetValueEx(new_key, "Application", 0, winreg.REG_SZ, "C:\\HboSoft\\HboUpdate.exe")
    # winreg.SetValueEx(new_key, "AppParameters", 0, winreg.REG_SZ, "hide")


def run_batch(batch):
    r = subprocess.Popen(batch,
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE).stdout.read()
    if sys.getdefaultencoding() != locale.getpreferredencoding():
        r = r.decode(locale.getpreferredencoding())
    return r
